package com.stan.core.mapper.factory;

import com.stan.core.conf.ConfManager;
import com.stan.core.contants.Constants;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

/**
 * 获得Mapper的Factory
 */
public class MapperFactory {
    /**
     * 单例模式
     */
    private MapperFactory(){
        // 加载MyBatis 配置文件
        String mybatisConfLoc = ConfManager.getProperty(Constants.MYBATIS_CONF_LOC);
        InputStream is = MapperFactory.class.getClassLoader().getResourceAsStream(mybatisConfLoc);
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        this.sqlSessionFactory = builder.build(is);
        sqlSession = sqlSessionFactory.openSession(true);
    }

    private static MapperFactory mapperFactory = null;
    public static MapperFactory getMapperFactory(){
        if(mapperFactory == null){
            synchronized (MapperFactory.class) {
                mapperFactory = new MapperFactory();
            }
        }
        return mapperFactory;
    }

    private SqlSession sqlSession;
    private SqlSessionFactory sqlSessionFactory;


    public SqlSession getSqlSession() {
        return sqlSession;
    }

    public SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }


    /**
     * 直接获得相应的mapper
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T getMapper(Class<T> clazz){
        if(sqlSession == null){
            this.sqlSession = sqlSessionFactory.openSession(true);
        }
        return sqlSession.getMapper(clazz);
    }

}
